#ifndef __BLOCKQUEUE_HPP__
#define __BLOCKQUEUE_HPP__
#include <iostream>
#include <queue>

// T -> commodity
template<typename T>
class BlockQueue
{
public:
    BlockQueue()
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_producer_cond, nullptr);
        pthread_cond_init(&_consumer_cond, nullptr);
    }

    void push(T& in)    // for producer
    {
        pthread_mutex_lock(&_mutex);
        if(isFull())    // wait for commodity number reduce
        {
            pthread_cond_wait(&_producer_cond, &_mutex);
        }

        // take 'in' val to queue back
        _block_queue.push(in);

        // judge by quantity whether to notify Consumer
        if((_block_queue.size()*10 / _capacity) >= 6)
        {
            pthread_cond_signal(&_consumer_cond);
        }

        pthread_mutex_unlock(&_mutex);
    }

    void pop(T* out)    // for consumer
    {
        pthread_mutex_lock(&_mutex);
        if(isEmpty())   // wait for new commodity
        {
            pthread_cond_wait(&_consumer_cond, &_mutex);
        }

        // consume and take val to 'out'
        *out = _block_queue.front();
        _block_queue.pop();

        // call Producer to make
        pthread_cond_signal(&_producer_cond);

        pthread_mutex_unlock(&_mutex);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_producer_cond);
        pthread_cond_destroy(&_consumer_cond);
    }
private:
    bool isFull()
    {
        return _block_queue.size() >= _capacity;
    }
    bool isEmpty()
    {
        return _block_queue.size() == 0;
    }
private:
    std::queue<T> _block_queue;
    size_t _capacity = 10;
    pthread_mutex_t _mutex;
    pthread_cond_t  _producer_cond;
    pthread_cond_t _consumer_cond;
};


#endif